package _8_Gorm框架老郭

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"time"
)

func main() {
	type Email struct {
		email string
	}
	type User struct {
		gorm.Model
		Name     string
		Age      uint
		Active   bool
		Role     string
		Birthday time.Time
	}
	var email Email
	var users []User

	dsn := "root:123456@tcp(127.0.0.1:3306)/golang_db?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("failed to connect darabase")
	}

	//删除一条记录时，删除对象需要指定主键，否则会触发 批量 Delete
	// Email 的 ID 是 `10`
	db.Delete(&email)
	// DELETE from emails where id = 10;

	// 带额外条件的删除
	db.Where("name = ?", "jinzhu").Delete(&email)
	// DELETE from emails where id = 10 AND name = "jinzhu";

	//根据主键删除
	db.Delete(&User{}, 10)
	// DELETE FROM users WHERE id = 10;

	db.Delete(&User{}, "10")
	// DELETE FROM users WHERE id = 10;

	db.Delete(&users, []int{1, 2, 3})
	// DELETE FROM users WHERE id IN (1,2,3);

	//批量删除
	db.Where("email LIKE ?", "%jinzhu%").Delete(&Email{})
	// DELETE from emails where email LIKE "%jinzhu%";

	db.Delete(&Email{}, "email LIKE ?", "%jinzhu%")
	// DELETE from emails where email LIKE "%jinzhu%";
}
